var express = require('express');
var router = express.Router();
var buyerDao = require("../bin/Dao/buyer.js");
var sellerDao = require("../bin/Dao/seller.js");


router.post("/regist", (req, res) => {
    if (req.body.kind == 'buyer') {
        var buyer = new buyerDao({
            username: req.body.username,
            psw: req.body.psw
        });
        buyer.save()
            .then(data => {
                if (data) {
                    res.json({ err: 0, msg: "注册成功！" });
                }
            })
        return;
    }
    var seller = new sellerDao({
        username: req.body.username,
        shopname:req.body.shopname,
        psw: req.body.psw
    });
    seller.save()
        .then(data => {
            if (data) {
                res.json({ err: 0, msg: "注册成功！" });
            }
        })
})

router.post("/login", (req, res) => {
    buyerDao.findOne(req.body, { psw: 0 })
        .then(data => {
            if (data) {
                var logmsg = {
                    id: data._id,
                    username: data.username,
                    kind: "buyer"
                }
                req.session.user = logmsg;
                res.json({ err: 0, data: req.session.user });
            }
            else {
                sellerDao.findOne(req.body)
                    .then(data2 => {
                        if (data2) {
                            var logmsg = {
                                _id: data2._id,
                                username: data2.username,
                                kind: "seller"
                            }
                            req.session.user = logmsg;
                            res.json({ err: 0, data: req.session.user });
                        } else {
                            res.json({ err: 1 })
                        }
                    })

            }
        })
})


router.get("/isLogin",(req,res)=>{
    // console.log("发送是否登录请求了")
    if(!req.session.user==''){
        // console.log("已经登录了")
        res.json({err:0,data:req.session.user});
        
    }else{
        // console.log("还没有登录")
         res.json({err:1})
    }
})


router.get("/logOut",(req,res)=>{
    // console.log("发送退出请求了");
    req.session.user='';
    // console.log(req.session)
    res.json({err:0,msg:"退出成功！"});
})

module.exports = router;
